package middleware

import (
	"github.com/gin-gonic/gin"
	"github.com/jmoiron/sqlx"
	"log"
	"net/http"
	"vip_video/configx"
	"vip_video/internal/library"
)

func AuthMiddleware(forceLogin bool, db *sqlx.DB, c *configx.Config) gin.HandlerFunc {
	return func(context *gin.Context) {
		//获取 header 里面的 token
		response := library.NewResponse(context)
		auth, err := library.AuthLibraryInstance(db).WithConfig(c).Init(context.GetHeader("token"))
		if err != nil && forceLogin {
			log.Printf("授权出现问题:%s", err.Error())
			response.WithResponseHttpCode(http.StatusUnauthorized).ErrorAbort("未授权")
			return
		}
		//设置到ctx里
		context.Set("auth", auth)
		context.Next()
	}
}
